package cn.wolfcode.job;

import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.feign.SeckillProductFeignApi;
import cn.wolfcode.redis.JobRedisKey;
import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Setter
@Getter
public class MyInitSeckillProductJob implements SimpleJob {
    @Autowired
    private SeckillProductFeignApi seckillProductFeignApi;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${jobCron.initSeckillProduct}")
    private String cron;

    @Override
    public void execute(ShardingContext shardingContext) {
        System.out.println(shardingContext.getShardingParameter());
        doWork(shardingContext.getShardingParameter());
    }

    private void doWork(String time) {
        //远程调用秒杀服务把数据查询出来   Result  data：List<SeckillProductVo>
        Result<List<SeckillProductVo>> result = seckillProductFeignApi.selectByTime(Integer.parseInt(time));
        /**
         * result的数据一共有三种情况：
         * 1、秒杀服务直接挂掉，走降级的方法返回值为null
         * 2、服务调用没问题，返回值为{code:200,msg:操作成功,data:List<SeckillProductVo>}
         * 3、秒杀服务内部出问题，返回值为{code:50201,msg:秒杀服务器繁忙}
         */
        if (result != null && !result.hasError()){
            List<SeckillProductVo> seckillProductVos = result.getData();
            if (seckillProductVos != null && seckillProductVos.size() > 0){
                //把查询来的数据存放到redis中
                for (SeckillProductVo seckillProductVo : seckillProductVos) {
                    redisTemplate.opsForHash().put(JobRedisKey.SECKILL_PRODUCT_LIST.getRealKey(time + ""),
                            seckillProductVo.getId()+"", JSON.toJSONString(seckillProductVo));
                    redisTemplate.opsForHash().put(JobRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(time + ""),
                            seckillProductVo.getId()+"",seckillProductVo.getStockCount() + "");
                }
            }
        }
    }
}
